package com.xgq.drink.filter;

import com.xgq.drink.entity.Role;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RedisUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 清除旧的认证信息
            SecurityContextHolder.clearContext();
            
            System.out.println("====== JWT Filter Processing Request: " + request.getRequestURI() + " ======");
            
            // 从请求解析出Token
            String token = resolveToken(request);
            System.out.println("Resolved token: " + (token != null ? token.substring(0, Math.min(10, token.length())) + "..." : "null"));
            
            // 验证Token
            if (token != null && !redisUtil.isTokenBlacklisted(token)) {
                try {
                    // 从Token中获取用户ID
                    String userIdStr = jwtTokenUtil.getUserIdFromToken(token);
                    System.out.println("User ID from token: " + userIdStr);
                    
                    if (userIdStr != null) {
                        Long userId = Long.parseLong(userIdStr);
                        // 从Redis中获取用户角色
                        System.out.println("尝试从Redis获取用户角色，用户ID: " + userId);
                        List<Role> roles = redisUtil.getUserRoles(userId.toString());
                        System.out.println("从Redis获取到的角色: " + (roles != null ? roles.size() + "个角色" : "null"));
                        
                        if (roles != null && !roles.isEmpty()) {
                            List<GrantedAuthority> authorities = new ArrayList<>();
                            
                            // 将角色转换为SpringSecurity的权限
                            for (Role role : roles) {
                                System.out.println("添加权限: " + role.getCode() + ", 角色ID: " + role.getId() + ", 角色名称: " + role.getName());
                                authorities.add(new SimpleGrantedAuthority(role.getCode()));
                            }
                            
                            // 创建认证对象
                            Authentication authentication = new UsernamePasswordAuthenticationToken(
                                    userId, null, authorities);
                            
                            // 设置认证信息
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            System.out.println("Authentication set in SecurityContext: " + authentication);
                        } else {
                            System.out.println("No roles found for user: " + userId);
                        }
                    } else {
                        System.out.println("Could not extract user ID from token");
                    }
                } catch (Exception e) {
                    System.out.println("Error processing token: " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                System.out.println("No valid token found or token is blacklisted");
            }
            
            // 继续过滤器链
            filterChain.doFilter(request, response);
            System.out.println("====== JWT Filter Completed ======");
        } catch (Exception e) {
            System.out.println("Error in JwtAuthenticationFilter: " + e.getMessage());
            e.printStackTrace();
            filterChain.doFilter(request, response);
        }
    }

    private String resolveToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }
} 